<?php

namespace app\model;

use think\facade\Cache;
use think\helper\Str;
use think\Model;

class User extends Model
{
    public function minLogin($openid): array
    {
        $data = $this->where('miniid', $openid)->where('state', 1)->where('is_del', 1)->find();
        if (empty($data)) {
            //自动注册
            $this->save([
                "user" => $this->setUserName(),
                "miniid" => $openid,
                "state" => 1,
                "is_del" => 1
            ]);
//            $data = $this;
        }
        $id = $data['id'] ?? $this->id;
        $token = setCacheToken("api");
        Cache::set("api_$token", ['uid' => $id, 'token' => $token], 86400 * 7);
        return ['uid' => $id, 'token' => $token];
    }

    protected function setUserName(): string
    {
        $name = "ZS-" . Str::random(8);
        $count = $this->where('user', $name)->count();
        if ($count > 0) return $this->setUserName();
        return $name;
    }
}
